package com.yingran.common.util;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.yingran.common.LogTool;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

import static android.os.Environment.DIRECTORY_MOVIES;
import static android.os.Environment.DIRECTORY_PICTURES;

/**
 * Created by Ksy.
 */

public class AndroidUtil {
    public static String regularPhone = "^1[3,4,5,6,7,8]+\\d{9}$";
    public String adb = "adb shell \"dumpsys activity activities | grep mFocusedActivity\"";
    public static final String tempFolder = "TongPao";
    public static final String tempCacheFolder = "TongPao/tempCache";
    public static final String tempImageFolder = "TongPao/tempImage";
    public static final String tempVoiceFolder = "TongPao/tempVoice";
    public static final String tempVideoFolder = "TongPao/tempVideo";
    public static final String voiceExt = ".amr";
    public static final String imageExt = ".jpeg";
    public static final String videoExt = ".mp4";

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public static int sp2px(float spValue) {
        DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
        final float fontScale = displayMetrics.scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int dip2px(float dp) {
        DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
        float px = dp * ((float) displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
        return (int) px;
    }


    private static File getStorageDir(Context context) {
        File var1 = Environment.getExternalStorageDirectory();
        if (var1.exists()) {
            return var1;
        }
        return context.getFilesDir();
    }


    public static int px2dip(float px) {
        DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
        float dp = px / ((float) displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
        return (int) dp;
    }

    public static void installApk(Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".fileurl", apkFile);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, context.getContentResolver().getType(uri));
        } else {
            Uri apkUri = Uri.fromFile(apkFile);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (wm == null) {
            return Resources.getSystem().getDisplayMetrics().widthPixels;
        }
        Point point = new Point();
        wm.getDefaultDisplay().getRealSize(point);
        return point.x;
    }

    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (wm == null) {
            return Resources.getSystem().getDisplayMetrics().heightPixels;
        }
        Point point = new Point();
        wm.getDefaultDisplay().getRealSize(point);
        return point.y;
    }

    public static boolean isMain() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    public static void notifyMedia(Context context, File file) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }

    public static String getTempImageName() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String formatDate = dateFormat.format(new Date());
        return formatDate + "_" + getRandom() + imageExt;
    }

    public static String getTempVoiceName() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String formatDate = dateFormat.format(new Date());
        return formatDate + "_" + getRandom() + voiceExt;
    }

    public static String getTempVideoName() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String formatDate = dateFormat.format(new Date());
        return formatDate + "_" + getRandom() + videoExt;
    }

    public static File getTempFileFolder(Context context) {
        File dir = new File(getStorageDir(context), tempFolder);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;

    }

    public static File getTempCacheFolder(Context context) {
        File dir = new File(getStorageDir(context), tempCacheFolder);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;

    }

    public static File getTempVoiceFolder(Context context) {
        File dir = new File(getStorageDir(context), tempVoiceFolder);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    public static File getTempVideoFolder(Context context) {
        File dir = new File(getStorageDir(context), tempVideoFolder);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    private static File getMediaImageStorageDir(Context context) {
        File var1 = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES);
        if (!var1.exists()) {
            var1.mkdirs();
        }
        return var1;
    }

    private static File getSystemDir(Context context) {
        return context.getFilesDir();
    }

    private static File getMediaVideoStorageDir(Context context) {
        File var1 = Environment.getExternalStoragePublicDirectory(DIRECTORY_MOVIES);
        if (!var1.exists()) {
            var1.mkdirs();
        }
        return var1;
    }

    public static File getTempSystemDirImageFile(Context context) {
        File file = new File(getSystemDir(context), getTempImageName());
        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    public static File getTempMediaImageFile(Context context) {
        File file = new File(getMediaImageStorageDir(context), getTempImageName());
        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    public static File getTempMediaVideoFile(Context context) {
        File file = new File(getMediaVideoStorageDir(context), getTempVideoName());
        if (file.exists()) {
            file.delete();
        }
        return file;
    }


    public static File getTempImageFile(Context context) {
        File dir = new File(getStorageDir(context), tempImageFolder);
        File file = new File(dir, getTempImageName());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (file.exists()) {
            file.delete();
        }
        return file;
    }


    public static File getTempVideoFile(Context context) {
        File dir = new File(getStorageDir(context), tempVideoFolder);
        File file = new File(dir, getTempVideoName());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    public static File getTempVideoFile(Context context, String fileName) {
        File dir = new File(getStorageDir(context), tempVideoFolder);
        File file = new File(dir, fileName + videoExt);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    public static File getVideoFile(Context context, String fileName) {
        File dir = new File(getStorageDir(context), tempVideoFolder);
        File file = new File(dir, fileName + videoExt);
        return file;
    }


    public static int getRandom() {
        Random random = new Random();
        int s = random.nextInt(9999) % (9999 - 1000 + 1) + 1000;
        return s;
    }


    public static void deleteFile(File file) {
        if (file == null) {
            return;
        }
        if (file.exists()) {
            try {
                file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteAllFiles(File file) {
        if (file == null) {
            return;
        }
        if (file.isFile()) {
            try {
                file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                try {
                    file.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
            for (File f : childFile) {
                deleteAllFiles(f);
            }
            try {
                file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static long getFileSize(File file) {
        long size = 0;
        if (file != null && file.exists() && file.isFile()) {
            size = file.length();
        }
        return size;
    }

    private static long getFileSizes(File file) {
        long size = 0;
        if (file == null) {
            return size;
        }
        File flist[] = file.listFiles();
        for (int i = 0; i < flist.length; i++) {
            File fileSub = flist[i];
            if (fileSub.isDirectory()) {
                size = size + getFileSizes(fileSub);
            } else {
                size = size + getFileSize(fileSub);
            }
        }
        return size;
    }

    public static String getFileOrFilesSize(File file) {
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FormatFileSize(blockSize);
    }

    private static String FormatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString;
        String wrongSize = "0KB";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    public static File getVideoThumb(Context context, String videoPath) {
        Bitmap videoThumbnail = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
        return bitmap2File(context, videoThumbnail);
    }

    public static File getVideoThumb(Context context, String videoPath, long time) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(videoPath);
            bitmap = retriever.getFrameAtTime(time * 1000);
        } catch (Exception ex) {
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
            }
        }
        if (bitmap == null) return null;
        return bitmap2File(context, bitmap);
    }

    public static List<Bitmap> getVideoThumbBitMap(String videoPath, List<Integer> times) {
        List<Bitmap> bitmaps = new ArrayList<>();
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(videoPath);
            for (int i = 0; i < times.size(); i++) {
                bitmaps.add(retriever.getFrameAtTime(times.get(i) * 1000));
            }
        } catch (Exception ex) {
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
            }
        }
        return bitmaps;
    }


    public static File getVideoThumb(Context context, String videoPath, int width, int height, int kind) {
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap2File(context, bitmap);
    }

    public static boolean copyFile(File fromFile, File toFile) {
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile, false);

            byte[] data = new byte[1024];
            int len;
            while ((len = from.read(data)) > -1) {
                to.write(data, 0, len);
            }
            to.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (from != null) {
                try {
                    from.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (to != null) {
                try {
                    to.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static long copyFile(InputStream from, File toFile) throws IOException {
        long totalBytes = 0;
        FileOutputStream fos = new FileOutputStream(toFile, false);
        try {
            byte[] data = new byte[1024];
            int len;
            while ((len = from.read(data)) > -1) {
                fos.write(data, 0, len);
                totalBytes += len;
            }
            fos.flush();
        } finally {
            fos.close();
        }
        return totalBytes;
    }

    public static File bitmap2File(Context context, Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        File tempImageFile = AndroidUtil.getTempImageFile(context);
        FileOutputStream fOut;
        try {
            fOut = new FileOutputStream(tempImageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.flush();
            fOut.close();
            bitmap.recycle();
            bitmap = null;
            System.gc();
        } catch (IOException e) {
            return null;
        }
        return tempImageFile;
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @SuppressLint("HardwareIds")
    public static String getIMEI(@NonNull Context context) {
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (tm == null) {
                return imei;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                imei = tm.getImei();
            } else {
                imei = tm.getDeviceId();
            }
            LogTool.e("获取IMEI码....." + imei);
        } catch (SecurityException exception) {
            LogTool.e("获取IMEI码没权限....." + exception);
        }
        if (TextUtils.isEmpty(imei)) {
            imei = UUID.randomUUID().toString();
        }
        return imei;
    }


    public static List<HashMap<String, String>> getContacts(Context context) {
//        SystemClock.sleep(3000);
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        // 1.获取内容解析者
        ContentResolver resolver = context.getContentResolver();
        // 2.获取内容提供者的地址:com.android.contacts
        // raw_contacts表的地址 :raw_contacts
        // view_data表的地址 : data
        // 3.生成查询地址
        Uri raw_uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri date_uri = Uri.parse("content://com.android.contacts/data");
        // 4.查询操作,先查询raw_contacts,查询contact_id
        // projection : 查询的字段
        Cursor cursor = resolver.query(raw_uri, new String[]{"contact_id"},
                null, null, null);
        // 5.解析cursor
        if (cursor == null) {
            return list;
        }
        while (cursor.moveToNext()) {
            // 6.获取查询的数据
            String contact_id = cursor.getString(0);
            // cursor.getString(cursor.getColumnIndex("contact_id"));//getColumnIndex
            // : 查询字段在cursor中索引值,一般都是用在查询字段比较多的时候
            // 判断contact_id是否为空
            if (!TextUtils.isEmpty(contact_id)) {//null   ""
                // 7.根据contact_id查询view_data表中的数据
                // selection : 查询条件
                // selectionArgs :查询条件的参数
                // sortOrder : 排序
                // 空指针: 1.null.方法 2.参数为null
                Cursor c = resolver.query(date_uri, new String[]{"data1",
                                "mimetype"}, "raw_contact_id=?",
                        new String[]{contact_id}, null);
                HashMap<String, String> map = new HashMap<String, String>();
                // 8.解析c
                if (c == null) {
                    return list;
                }
                while (c.moveToNext()) {
                    // 9.获取数据
                    String data1 = c.getString(0);
                    String mimetype = c.getString(1);
                    // 10.根据类型去判断获取的data1数据并保存
                    if (mimetype.equals("vnd.android.cursor.item/phone_v2")) {
                        // 电话
                        map.put("phone", data1);
                    } else if (mimetype.equals("vnd.android.cursor.item/name")) {
                        // 姓名
                        map.put("name", data1);
                    }
                }
                // 11.添加到集合中数据
                list.add(map);
                // 12.关闭cursor
                c.close();
            }
        }
        // 12.关闭cursor
        cursor.close();
        return list;
    }

    public static int getStatusBarHeight(Context context) {
        int result = dip2px(25);
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        }
        return false;
    }


    public static ParamsUtil.ParamsThree<Integer, Integer, Long> getVideoParams(String videoPath) {
        long duration = 0;
        int with = 0;
        int height = 0;
        MediaMetadataRetriever mMetadataRetriever = new MediaMetadataRetriever();
        try {
            mMetadataRetriever.setDataSource(videoPath);
            with = Integer.parseInt(mMetadataRetriever.extractMetadata
                    (MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
            height = Integer.parseInt(mMetadataRetriever.extractMetadata
                    (MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
            duration = Long.parseLong(mMetadataRetriever.extractMetadata
                    (MediaMetadataRetriever.METADATA_KEY_DURATION));
            return ParamsUtil.getInstance().create(with, height, duration);
        } catch (Exception e) {
            e.printStackTrace();
            return ParamsUtil.getInstance().create(with, height, duration);
        } finally {
            try {
                mMetadataRetriever.release();
            } catch (RuntimeException ex) {
            }
        }
    }

    public static String money(String moneyString) {
        return money(moneyString, true);
    }

    public static String money(String moneyString, boolean isWithXiaoShu) {
        try {
            double money = Double.parseDouble(moneyString);
            return money(money, isWithXiaoShu);
        } catch (Exception e) {
            e.printStackTrace();
            if (isWithXiaoShu) {
                return "0.00元";
            }
            return "0元";
        }
    }

    public static String money(double money) {
        return money(money, true);
    }

    public static String money(double money, boolean isWithXiaoShu) {
        if (money == 0) {
            if (isWithXiaoShu) {
                return "0.00元";
            }
            return "0元";
        }
        try {
            BigDecimal bd = new BigDecimal(money);
            DecimalFormat df = new DecimalFormat(",###,####.00");
            String formatMoney = df.format(bd);
            if (isWithXiaoShu) {
                return formatMoney + "\u0020元";
            }
            if (formatMoney.contains(".")) {
                String moneyZhengShuString = formatMoney.substring(0, formatMoney.indexOf("."));
                String moneyXiaoShuString = formatMoney.substring(formatMoney.indexOf(".") + 1, formatMoney.length());
                float moneyXiaoshu = Float.parseFloat(moneyXiaoShuString);
                LogTool.e("moneyXiaoShuString   " + moneyXiaoShuString + "  moneyXiaoshu    " + moneyXiaoshu);
                if (moneyXiaoshu == 0) {
                    return moneyZhengShuString + "\u0020元";
                }
            }
            return formatMoney + "\u0020元";
        } catch (Exception e) {
            e.printStackTrace();
            if (isWithXiaoShu) {
                return "0.00元";
            }
            return "0元";
        }
    }

    public static boolean isSingleActivity(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = null;
        if (activityManager == null) {
            return false;
        }
        try {
            runningTaskInfos = activityManager.getRunningTasks(1);
        } catch (SecurityException var4) {
            var4.printStackTrace();
        }

        if (runningTaskInfos != null && runningTaskInfos.size() >= 1) {
            return (runningTaskInfos.get(0)).numRunning == 1;
        } else {
            return false;
        }
    }

    public static boolean isNetImage(String imageUrl) {
        return !TextUtils.isEmpty(imageUrl) && (imageUrl.toLowerCase().startsWith("http://") || imageUrl.toLowerCase().startsWith("https://"));
    }

    public static boolean isRemoteHtml(String htmlUrl) {
        return !TextUtils.isEmpty(htmlUrl) && (htmlUrl.toLowerCase().startsWith("http://") || htmlUrl.toLowerCase().startsWith("https://"));

    }

    public static File putRes2Path(Context context, int resId) {
        try {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
            if (bitmap != null) {
                File file = AndroidUtil.bitmap2File(context, bitmap);
                if (file != null && file.exists() && file.isFile() && file.canRead()) {
                    return file;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
